<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8" />
    <title>订单节点</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
    <link rel="stylesheet" href="/app/admin/admin/css/pages/orderdetail.css" />
  </head>
  <body class="pear-container">
    <!-- 顶部查询表单 -->
    <div class="layui-card">
      <div class="layui-card-body">
        <form class="layui-form top-search-from">
          <input type="hidden" name="order_id" value="<?=$order_id?>" id="order_id"/>
          <input type="hidden" name="user_id" value="<?=$user_id?>" class="layui-input"/>

          <?php if ($user_id > 0): ?>
          <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
            <ul class="layui-tab-title" id="typeData"></ul>
          </div>
          <div class="layui-tab-content"></div>
          <input type="hidden" name="line_id" value="" id="line_id">
          <?php else: ?>
          <?php endif; ?>

          <div class="layui-form-item">
            <label class="layui-form-label">订单号</label>
            <div class="layui-input-block">
              <input
                type="hidden"
                autocomplete="off"
                name="order_no[]"
                value="like"
                class="layui-input inline-block"
              />
              <input
                type="text"
                autocomplete="off"
                name="order_no[]"
                class="layui-input"
              />
            </div>
          </div>

          <?php if ($user_id > 0): ?>
          <?php else: ?>
          <div class="layui-form-item">
            <label class="layui-form-label">线路</label>
            <div class="layui-input-block">
              <div name="line_id" id="line_id" value=""></div>
            </div>
          </div>
          <?php endif; ?>

          <div class="layui-form-item">
            <label class="layui-form-label">项目</label>
            <div class="layui-input-block">
              <div name="game_id" id="game_id" value=""></div>
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">有效期</label>
            <div class="layui-input-block">
              <div name="status" id="status" value=""></div>
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">到期时间</label>
            <div class="layui-input-block">
              <div class="layui-input-block" id="expire_time">
                <input
                  type="text"
                  autocomplete="off"
                  name="expire_time[]"
                  id="expire_time-date-start"
                  class="layui-input inline-block"
                  placeholder="开始时间"
                />
                -
                <input
                  type="text"
                  autocomplete="off"
                  name="expire_time[]"
                  id="expire_time-date-end"
                  class="layui-input inline-block"
                  placeholder="结束时间"
                />
              </div>
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">ip</label>
            <div class="layui-input-block">
              <input
                type="hidden"
                autocomplete="off"
                name="ip[]"
                value="like"
                class="layui-input inline-block"
              />
              <input
                type="text"
                autocomplete="off"
                name="ip[]"
                class="layui-input"
              />
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
              <input
                type="hidden"
                autocomplete="off"
                name="account[]"
                value="like"
                class="layui-input inline-block"
              />
              <input
                type="text"
                autocomplete="off"
                name="account[]"
                class="layui-input"
              />
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">时长类型</label>
            <div class="layui-input-block">
              <div name="duration" id="duration" value=""></div>
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">自动续费</label>
            <div class="layui-input-block">
              <div name="renew_status" id="renew_status" value=""></div>
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">分组</label>
            <div class="layui-input-block">
              <input type="text" name="group" value="" class="layui-input" />
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
              <input
                type="hidden"
                autocomplete="off"
                name="remark[]"
                value="like"
                class="layui-input inline-block"
              />
              <input
                type="text"
                autocomplete="off"
                name="remark[]"
                class="layui-input"
              />
            </div>
          </div>

          <div class="layui-form-item layui-inline">
            <label class="layui-form-label"></label>
            <button
              class="pear-btn pear-btn-md pear-btn-primary"
              lay-submit
              lay-filter="table-query"
            >
              <i class="layui-icon layui-icon-search"></i>查询
            </button>
            <button
              type="reset"
              class="pear-btn pear-btn-md"
              lay-submit
              lay-filter="table-reset"
            >
              <i class="layui-icon layui-icon-refresh"></i>重置
            </button>
          </div>
          <div class="toggle-btn">
            <a class="layui-hide"
              >展开<i class="layui-icon layui-icon-down"></i
            ></a>
            <a class="layui-hide"
              >收起<i class="layui-icon layui-icon-up"></i
            ></a>
          </div>
        </form>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="layui-card">
      <div class="layui-card-body">
        <table id="data-table" lay-filter="data-table"></table>
      </div>
    </div>

    <!-- 表格顶部工具栏 -->
    <?php if ($user_id > 0): ?>

    <script type="text/html" id="table-toolbar">
      <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="export">
        导出
      </button>
      <button plain class="pear-btn pear-btn-primary pear-btn-md mr8" lay-event="copy">
        复制
      </button>
      <button plain class="pear-btn pear-btn-primary pear-btn-md mr8" lay-event="group">
        分组
      </button>
      <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="remark">
        备注
      </button>
      <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="renew">
        续费
      </button>
      <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="transfer-ownership">
        过户
      </button>
      <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="average-time">
        平均时间
      </button>
      <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="change-password">
        改密
      </button>
      <button plain class="pear-btn pear-btn-primary pear-btn-md" id="more_change_ip">
        调换IP
        <i class="layui-icon layui-icon-triangle-d"></i>
      </button>

      <?php if ($config['order_node_renew_auto']): ?>
      <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="renewAutoOpen">自动续费开启</button>
      <?php else: ?>
      <?php endif; ?>

      <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="renewAutoOff">自动续费关闭</button>
      <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="bind">解绑</button>
    </script>

    <?php else: ?>

    <script type="text/html" id="table-toolbar">
      <button plain class="pear-btn pear-btn-primary pear-btn-md mr8" lay-event="group">
        分组
      </button>
      <button plain class="pear-btn pear-btn-primary pear-btn-md" lay-event="remark">
        备注
      </button>

    </script>

    <?php endif; ?>

    <!-- 表格行工具栏 -->
    <script type="text/html" id="table-bar">
<!--        <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="app.admin.v1ordernode.update">编辑</button>-->
<!--        <button class="pear-btn pear-btn-xs tool-btn" lay-event="remove" permission="app.admin.v1ordernode.delete">删除</button>-->
    </script>

    <!-- 续费 WRAPPER_BOX -->
    <div id="renew-wrapper" style="display: none">
      <div id="renew-table"></div>
      <div class="renew-footer flex align-center justify-between">
        <div class="tips-left">
          <!-- 已选续费数量1条，应付1.5积分， 成功0条，失败0条 -->
        </div>
        <div class="tips-right flex align-center">
          <div class="tips-right__1 flex align-center mr8">
            <span>续费时间：</span>
            <div id="select-time" name="select-time"></div>
          </div>
          <div class="tips-right__2">
            <button class="pear-btn pear-btn-primary" id="confirm-renew">
              确认续费
            </button>
            <button class="pear-btn" id="cancel-renew">取消</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 过户 WRAPPER_BOX -->
    <div id="transfer-ownership-wrapper" style="display: none">
      <div id="transfer-os-table" lay-filter="transfer-os-table"></div>
      <div class="fransfer-os-footer flex align-center justify-between">
        <div class="placeholder"></div>
        <div class="tips-right flex align-center">
          <div class="tips-right__1 flex align-center mr8">
            <input
              type="text"
              placeholder="请输入用户名称进行搜索"
              class="layui-input transfer-input"
            />
          </div>
          <div class="tips-right__2">
            <button class="pear-btn pear-btn-primary" id="search-users">
              搜索用户
            </button>
            <button class="pear-btn" id="search-users-cancel">取消</button>
          </div>
        </div>
      </div>
    </div>
    <!-- 过户 - 操作 -->
    <script type="text/html" id="transfer-os-bar">
      <a lay-event="transfer-ownership" class="mr-1"
        ><i class="pear-icon  pear-icon-release"></i>过户</a
      >
    </script>

    <!-- 平均时间 -->
    <div id="average-time-wrapper" style="display: none">
      <div id="average-timebox"></div>
      <div class="bn-times">
        <input
          type="text"
          name="expire_time_average_time"
          id="expire_time_average_time"
          autocomplete="off"
          class="layui-input"
          placeholder="请输入平均时间"
        />
        <ul></ul>
      </div>
    </div>

    <!-- 修改密码 -->
    <div id="change-password-wrapper" style="display: none">
      <div style="padding: 10px">
        <input
          type="text"
          id="change-password-input"
          class="layui-input"
          placeholder="请输入新密码"
          style="max-width: 290px"
        />
      </div>
      <div id="change-password"></div>
    </div>

    <!-- 同地区调换 -->
    <div id="change-same-area-wrapper" style="display: none">
      <div
        class="layui-tab layui-tab-brief"
        lay-filter="change-same-area-tab"
        style="display: none"
      >
        <ul class="layui-tab-title"></ul>
        <!-- <div class="layui-tab-content" style="height: 1px">
          <div class="layui-tab-item layui-show"></div>
          <div class="layui-tab-item"></div>
          <div class="layui-tab-item"></div>
          <div class="layui-tab-item"></div>
          <div class="layui-tab-item"></div>
        </div> -->
      </div>
      <div id="change-same-area-table"></div>
      <form
        onsubmit="return false;"
        class="layui-form"
        lay-filter="change-same-area-form"
      >
        <div class="layui-form-item">
          <label class="layui-form-label">自定义账号</label>
          <div class="layui-input-block" id="custom-accounts"></div>
        </div>
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">账号</label>
            <div class="layui-input-block">
              <input
                type="text"
                name="account"
                lay-verify="required"
                placeholder="请输入账号"
                autocomplete="off"
                class="layui-input"
              />
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-inline" style="max-width: 300px">
              <input
                type="text"
                name="pass"
                autocomplete="off"
                class="layui-input"
                placeholder="请输入密码"
              />
            </div>
          </div>
        </div>
        <!-- NOTE: 指定地区调换才展示自动输入 -->
        <div class="layui-form-item" style="display: none" type="appoint">
          <label class="layui-form-label">自动输入</label>
          <div class="layui-input-block">
            <div class="layui-inline">
              <input
                class="layui-input number-input-value"
                type="number"
                style="max-width: 180px"
                min="0"
                placeholder="节点数量"
                readonly
              />
            </div>
            <div class="layui-inline">
              <button
                class="pear-btn pear-btn-sm pear-btn-primary"
                id="autoinput-confirm"
              >
                <i class="layui-icon layui-icon-ok"></i>
                确认
              </button>
              <button class="pear-btn pear-btn-sm" id="autoinput-cancel">
                <i class="layui-icon layui-icon-close"></i>
                清空
              </button>
            </div>
            <div class="layui-inline">
              <!-- 提交信息 -->
              <div
                class="layui-input-inline layui-input-inline--autow flex align-center bn-submit-box"
              >
                <div>
                  剩余调换次数
                  <span class="point-score text-color-blue" id="max-count"
                    >0</span
                  >
                </div>
                <div>
                  <!-- <i class="layui-icon layui-icon-website text-color-blue"></i> -->
                  待选
                  <span class="point-score text-color-blue" id="wait-count"
                    >0</span
                  >
                </div>
                <div>
                  <i class="layui-icon layui-icon-senior text-color-blue"></i
                  >已选地区<span
                    class="point-score text-color-blue"
                    id="sel-area-count"
                    >0</span
                  >台
                </div>
                <div>
                  <i class="layui-icon layui-icon-website text-color-blue"></i
                  >已选总IP<span
                    class="point-score text-color-blue"
                    id="sel-ip-count"
                    >0</span
                  >台
                </div>
                <!-- <div>
                  <i class="layui-icon layui-icon-cellphone text-color-blue"></i
                  >消耗金币<span
                    class="point-score text-color-blue"
                    id="sel-score-count"
                    >0</span
                  >
                </div> -->
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="layui-form-item">
          <label class="layui-form-label">自选端口</label>
          <div class="layui-input-block">
            <div id="custom-port" name="custom-port"></div>
          </div>
        </div> -->
      </form>
    </div>

    <!-- 订单确认 -->
    <div class="order-confirm-wrapper" style="display: none">
      <table id="confirm-order-table" lay-filter="confirm-order-table"></table>
    </div>

    <script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
    <script src="/app/admin/component/pear/pear.js"></script>
    <script src="/app/admin/admin/js/permission.js"></script>
    <script src="/app/admin/admin/js/common.js"></script>
    <script src="/app/admin/admin/js/v1-order-node.js"></script>
    <script src="/app/admin/admin/js/order-node-apis.js"></script>

    <script>
      let defaultOrderId = '<?=$order_id?>';
      let defaultUserId = '<?=$user_id?>';
      let defaultLineId = '<?=$line_id?>';

      // 相关常量
      const PRIMARY_KEY = 'id'
      const SELECT_API = '/app/admin/v1-order-node/select'
      const UPDATE_API = '/app/admin/v1-order-node/update'
      const DELETE_API = '/app/admin/v1-order-node/delete'
      const INSERT_URL = '/app/admin/v1-order-node/insert'
      const UPDATE_URL = '/app/admin/v1-order-node/update'

      const GROUP_API = '/app/admin/v1-order-node/group'
      const REMARK_API = '/app/admin/v1-order-node/remark'
      const ORDERDETAIL_GAME_URL = '/app/admin/v1-node/orderdetail_game'
      const RENEW_AUTO_OPEN_API = '/app/admin/v1-api/renewAutoOpen'
      const BIND_API = '/app/admin/v1-api/bind'
      let configText = "<?=$config['text']?>"

      if(!defaultUserId){
        // 字段 线路ID line_id
        layui.use(['jquery', 'xmSelect', 'popup'], function () {
          layui.$.ajax({
            url: '/app/admin/v1-line/select2?format=tree',
            data: {
              field: 'weight',
              order: 'desc',
            },
            dataType: 'json',
            success: function (res) {
              let value = layui.$('#line_id').attr('value')
              let initValue = value ? value.split(',') : []
              layui.xmSelect.render({
                el: '#line_id',
                name: 'line_id',
                initValue: initValue,
                filterable: true,
                data: res.data,
                model: { icon: 'hidden', label: { type: 'text' } },
                clickClose: true,
                radio: true,
              })
              if (res.code) {
                layui.popup.failure(res.msg)
              }
            },
          })
        })
      }

      // 字段 游戏ID game_id
      layui.use(['jquery', 'xmSelect', 'popup'], function () {
        layui.$.ajax({
          url: '/app/admin/v1-game/select2?format=tree',
          data: {
            field: PRIMARY_KEY,
            order: 'desc',
          },
          dataType: 'json',
          success: function (res) {
            let value = layui.$('#game_id').attr('value')
            let initValue = value ? value.split(',') : []
            layui.xmSelect.render({
              el: '#game_id',
              name: 'game_id',
              initValue: initValue,
              filterable: true,
              data: res.data,
              model: { icon: 'hidden', label: { type: 'text' } },
              clickClose: true,
              radio: true,
            })
            if (res.code) {
              layui.popup.failure(res.msg)
            }
          },
        })
      })

      // 字段 时长类型 duration
      layui.use(['jquery', 'xmSelect', 'popup'], function () {
        layui.$.ajax({
          url: '/app/admin/dict/getNew/get_duration_type_list',
          dataType: 'json',
          success: function (res) {
            let value = layui.$('#duration').attr('value')
            let initValue = value ? value.split(',') : []
            layui.xmSelect.render({
              el: '#duration',
              name: 'duration',
              initValue: initValue,
              filterable: true,
              data: res.data,
              model: { icon: 'hidden', label: { type: 'text' } },
              clickClose: true,
              radio: true,
            })
            if (res.code) {
              layui.popup.failure(res.msg)
            }
          },
        })
      })

      // 字段 状态:0=未过期,1=已过期 status
      layui.use(['jquery', 'xmSelect', 'popup'], function () {
        layui.$.ajax({
          url: '/app/admin/dict/getNew/get_expire_status_list',
          dataType: 'json',
          success: function (res) {
            let value = layui.$('#status').attr('value')
            let initValue = value ? value.split(',') : []
            layui.xmSelect.render({
              el: '#status',
              name: 'status',
              initValue: initValue,
              filterable: true,
              data: res.data,
              model: { icon: 'hidden', label: { type: 'text' } },
              clickClose: true,
              radio: true,
            })
            if (res.code) {
              layui.popup.failure(res.msg)
            }
          },
        })
      })

      // 字段 自动续费 renew_status
      layui.use(['jquery', 'xmSelect', 'popup'], function () {
        layui.$.ajax({
          url: '/app/admin/dict/getNew/get_open_off_list',
          dataType: 'json',
          success: function (res) {
            let value = layui.$('#renew_status').attr('value')
            let initValue = value ? value.split(',') : []
            layui.xmSelect.render({
              el: '#renew_status',
              name: 'renew_status',
              initValue: initValue,
              filterable: true,
              data: res.data,
              model: { icon: 'hidden', label: { type: 'text' } },
              clickClose: true,
              radio: true,
            })
            if (res.code) {
              layui.popup.failure(res.msg)
            }
          },
        })
      })

      // 字段 到期时间 expire_time
      layui.use(['laydate'], function () {
        layui.laydate.render({
          elem: '#expire_time',
          range: ['#expire_time-date-start', '#expire_time-date-end'],
        })
      })

      // 表格渲染
      layui.use(['table', 'form', 'common', 'popup', 'util','notice'], function () {
        let table = layui.table
        let form = layui.form
        let $ = layui.$
        let common = layui.common
        let util = layui.util

        // 表头参数
        let cols = [
          {
            type: 'checkbox',
            align: 'left',
            width: 50,
          },
          {
            title: '主键',
            align: 'left',
            field: 'id',
            sort: true,
            width: 110,
          },
          {
            title: '自动续费',
            align: 'left',
            field: 'renew_status',
            templet: function (d) {
              let field = 'renew_status'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return util.escape(items.join(','))
            },
            width: 100,
          },
          {
            title: '订单号',
            align: 'left',
            field: 'order_no',
            width: 220,
          },
          {
            title: '购买用户',
            align: 'left',
            field: 'user_name',
            width: 150,
          },
          {
            title: '线路',
            align: 'left',
            field: 'line_id',
            templet: function (d) {
              let field = 'line_id'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return util.escape(items.join(','))
            },
            width: 200,
          },
          {
            title: '项目',
            align: 'left',
            field: 'game_id',
            templet: function (d) {
              let field = 'game_id'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return util.escape(items.join(','))
            },
            width: 200,
          },
          {
            title: '地区',
            align: 'left',
            field: 'region_id',
            templet: function (d) {
              let field = 'region_id'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return util.escape(items.join(','))
            },
            width: 200,
          },
          {
            title: '节点编号',
            align: 'left',
            field: 'code',
            width: 150,
          },
          {
            title: '域名',
            align: 'left',
            field: 'domain',
            hide: true,
            width: 150,
          },
          {
            title: 'ip',
            align: 'left',
            field: 'ip',
            width: 150,
          },
          {
            title: '端口',
            align: 'left',
            field: 'port',
            width: 100,
          },
          {
            title: '用户名',
            align: 'left',
            field: 'account',
            width: 120,
          },
          {
            title: '密码',
            align: 'left',
            field: 'pass',
            width: 120,
          },
          {
            title: '购买时间',
            align: 'left',
            field: 'created_at',
            width: 160,
          },
          {
            title: '到期时间',
            align: 'left',
            field: 'expire_time',
            width: 160,
          },
          {
            title: '来源类型',
            align: 'left',
            field: 'source',
            templet: function (d) {
              let field = 'source'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return util.escape(items.join(','))
            },
            width: 100,
          },
          {
            title: '分组',
            align: 'left',
            field: 'group',
            width: 100,
          },
          {
            title: '备注',
            align: 'left',
            field: 'remark',
            width: 160,
          },
          {
            title: '时长类型',
            align: 'left',
            field: 'duration',
            templet: function (d) {
              let field = 'duration'
              if (typeof d[field] == 'undefined') return ''
              let items = []
              layui.each((d[field] + '').split(','), function (k, v) {
                items.push(apiResults[field][v] || v)
              })
              return util.escape(items.join(','))
            },
            width: 110,
          },
          {
            title: '金币',
            align: 'left',
            field: 'amount',
            width: 100,
          },
          // {
          // 	title: "操作",
          // 	toolbar: "#table-bar",
          // 	align: "left",
          // 	fixed: "right",
          // 	width: 120,
          // }
        ]

        // 渲染表格
        function render() {
          table.render({
            elem: '#data-table',
            url: SELECT_API,
            page: true, // 是否显示分页
            limits: [20,100, 200, 300,400,500,600,700,800,900,1000],
            limit: 100, // 每页默认显示的数量
            cols: [cols],
            skin: 'line',
            size: 'lg',
            toolbar: '#table-toolbar',
            autoSort: false,
            defaultToolbar: [
              {
                title: '刷新',
                layEvent: 'refresh',
                icon: 'layui-icon-refresh',
              },
              'filter',
              'print',
              'exports',
            ],
            done: function () {
              layer.photos({ photos: 'div[lay-id="data-table"]', anim: 5 })
              renderDropdown(layui.dropdown)
            },
            where: {
              // 向服务端传递的额外参数
              field: PRIMARY_KEY, // 默认排序的字段
              order: 'desc', // 默认排序方式：asc（升序）或desc（降序）
              order_id: defaultOrderId,
              user_id: defaultUserId,
              line_id: defaultLineId,
            },
            initSort: {
              field: PRIMARY_KEY, // 默认排序的字段
              type: 'desc', // 默认排序方式：asc（升序）或desc（降序）
            },
          })
        }

        // 获取表格中下拉或树形组件数据
        let apis = []
        apis.push(['line_id', '/app/admin/v1-line/select2?format=tree'])
        apis.push(['game_id', '/app/admin/v1-game/select2?format=tree'])
        apis.push(['duration', '/app/admin/dict/getNew/get_duration_type_list'])
        apis.push(['region_id', '/app/admin/v1-region/select2?format=tree'])
        apis.push(['source', '/app/admin/dict/getNew/get_source_type_list'])
        apis.push(['renew_status', '/app/admin/dict/getNew/get_open_off_list'])
        let apiResults = {}
        apiResults['line_id'] = []
        apiResults['game_id'] = []
        apiResults['duration'] = []
        apiResults['region_id'] = []
        apiResults['source'] = []
        apiResults['renew_status'] = []
        let count = apis.length
        layui.each(apis, function (k, item) {
          let [field, url] = item
          $.ajax({
            url: url,
            dateType: 'json',
            success: function (res) {
              if (res.code) {
                return layui.popup.failure(res.msg)
              }
              function travel(items) {
                for (let k in items) {
                  let item = items[k]
                  apiResults[field][item.value] = item.name
                  if (item.children) {
                    travel(item.children)
                  }
                }
              }
              travel(res.data)
            },
            complete: function () {
              if (--count === 0) {
                render()
              }
            },
          })
        })
        if (!count) {
          render()
        }

        // 编辑或删除行事件
        table.on('tool(data-table)', function (obj) {
          if (obj.event === 'remove') {
            remove(obj)
          } else if (obj.event === 'edit') {
            edit(obj)
          }
        })

        // 表格顶部工具栏事件
        table.on('toolbar(data-table)', function (obj) {
          switch (obj.event) {
            case 'add':
              add()
              break
            case 'refresh':
              refreshTable()
              break
            case 'batchRemove':
              batchRemove(obj)
              break
            case 'export':
              exportTxt(obj)
              break
            case 'copy':
              __copy_txt__(obj)
              break
            case 'group':
              group(obj)
              break
            case 'remark':
              remark(obj)
              break
            case 'renew':
              __renew_operate__(obj)
              break
            case 'transfer-ownership':
              __transfer_ownership__(obj)
              break
            case 'average-time':
              __average_time__(obj)
              break
            case 'change-password':
              __change_password__(obj)
              break
            case 'renewAutoOpen':
              renewAutoOpen(obj, 1)
              break
            case 'renewAutoOff':
              renewAutoOpen(obj, 0)
              break
            case 'bind':
              bind(obj)
              break
          }
        })

        // 表格顶部搜索事件
        form.on('submit(table-query)', function (data) {
          data.field.field = PRIMARY_KEY
          data.field.order = 'desc'
          console.log(data, 'table-query')
          table.reload('data-table', {
            page: {
              curr: 1,
            },
            where: data.field,
          })
          return false
        })

        // 表格顶部搜索重置事件
        form.on('submit(table-reset)', function (data) {
          let data1 = {}
          data1.field = PRIMARY_KEY
          data1.order = 'desc'
          data1.order_id = defaultOrderId
          data1.user_id= defaultUserId
          data1.line_id= defaultLineId
          console.log(data1, 'table-reset')
          table.reload('data-table', {
            where: data1,
          })
        })

        // 字段允许为空
        form.verify({
          phone: [/(^$)|^1\d{10}$/, '请输入正确的手机号'],
          email: [
            /(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
            '邮箱格式不正确',
          ],
          url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, '链接格式不正确'],
          number: [/(^$)|^\d+$/, '只能填写数字'],
          date: [
            /(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/,
            '日期格式不正确',
          ],
          identity: [
            /(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/,
            '请输入正确的身份证号',
          ],
        })

        // 表格排序事件
        table.on('sort(data-table)', function (obj) {
          let data = obj.config.where
          data.field = obj.field
          data.order = obj.type
          console.log(data, 'obj')
          table.reload('data-table', {
            initSort: obj,
            scrollPos: 'fixed',
            where: data,
            // where: {
            //     field: obj.field,
            //     order: obj.type
            // }
          })
        })

        // 表格新增数据
        let add = function () {
          layer.open({
            type: 2,
            title: '新增',
            shade: 0.1,
            maxmin: true,
            area: [
              common.isModile() ? '100%' : '60%',
              common.isModile() ? '100%' : '95%',
            ],
            content: INSERT_URL,
            skin: '',
          })
        }

        // 表格编辑数据
        let edit = function (obj) {
          let value = obj.data[PRIMARY_KEY]
          layer.open({
            type: 2,
            title: '修改',
            shade: 0.1,
            maxmin: true,
            area: [
              common.isModile() ? '100%' : '60%',
              common.isModile() ? '100%' : '95%',
            ],
            content: UPDATE_URL + '?' + PRIMARY_KEY + '=' + value,
            skin: '',
          })
        }

        // 删除一行
        let remove = function (obj) {
          return doRemove(obj.data[PRIMARY_KEY])
        }

        // 删除多行
        let batchRemove = function (obj) {
          let checkIds = common.checkField(obj, PRIMARY_KEY)
          if (checkIds === '') {
            layui.popup.warning('未选中数据')
            return false
          }
          doRemove(checkIds.split(','))
        }

        // 执行删除
        let doRemove = function (ids) {
          let data = {}
          data[PRIMARY_KEY] = ids
          layer.confirm(
            '确定删除?',
            {
              icon: 3,
              title: '提示',
            },
            function (index) {
              layer.close(index)
              let loading = layer.load()
              $.ajax({
                url: DELETE_API,
                data: data,
                dataType: 'json',
                type: 'post',
                success: function (res) {
                  layer.close(loading)
                  if (res.code) {
                    return layui.popup.failure(res.msg)
                  }
                  return layui.popup.success('操作成功', refreshTable)
                },
              })
            }
          )
        }

        // 刷新表格数据
        window.refreshTable = function () {
          table.reloadData('data-table', {
            scrollPos: 'fixed',
            done: function (res, curr) {
              if (curr > 1 && res.data && !res.data.length) {
                curr = curr - 1
                table.reloadData('data-table', {
                  page: {
                    curr: curr,
                  },
                })
              }
            },
          })
        }


        /*-------按钮操作----------*/

        //   导出选中数据文本
        let exportTxt = function (obj) {
          let data = table.checkStatus(obj.config.id).data
          if (!data || !data.length) return layui.popup.warning('未选中数据')
          openExportData(data)
          // const dataStr = data
          //   .map(
          //     (item) =>
          //       `${item.ip}|${item.port}|${item.account}|${item.pass}|${item.expire_time}`
          //   )
          //   .join('\n')
          // downloadTextAsFile(dataStr)
        }

        //   复制选中数据 格式 xx|xx|xx|xx
        let __copy_txt__ = function (obj) {
          let data = table.checkStatus(obj.config.id).data
          if (!data || !data.length) return layui.popup.warning('未选中数据')
          const dataStr = data
            .map(
              (item) =>
                `${item.ip}|${item.port}|${item.account}|${item.pass}|${item.expire_time}`
            )
            .join('\n')
          copyText(dataStr)
        }

        // 分组
        let group = function (obj) {
          let checkIds = common.checkField(obj, PRIMARY_KEY)
          if (checkIds === '') {
            layui.popup.warning('未选中数据')
            return false
          }
          doGroup(checkIds.split(','))
        }

        // 执行分组
        let doGroup = function (ids) {
          let data = {}
          data[PRIMARY_KEY] = ids

          layer.prompt(
            { title: '请输入分组数字' },
            function (value1, index, elem) {
              let group = value1
              if (group === '') {
                return layui.popup.failure('请输入分组数字')
              }

              layer.close(index)
              let loading = layer.load()
              $.ajax({
                url: GROUP_API,
                data: { id: ids, group: group },
                dataType: 'json',
                type: 'post',
                success: function (res) {
                  layer.close(loading)
                  if (res.code) {
                    return layui.popup.failure(res.msg)
                  }
                  return layui.popup.success(res.msg, refreshTable)
                },
                error: function () {
                  layer.close(loading)
                  return layui.popup.failure('网络错误')
                },
              })
            }
          )
        }

        // 备注
        let remark = function (obj) {
          let checkIds = common.checkField(obj, PRIMARY_KEY)
          if (checkIds === '') {
            layui.popup.warning('未选中数据')
            return false
          }
          doRemark(checkIds.split(','))
        }

        // 执行备注
        let doRemark = function (ids) {
          let data = {}
          data[PRIMARY_KEY] = ids

          layer.prompt({ title: '请输入备注' }, function (value1, index, elem) {
            let remark = value1
            if (remark === '') {
              return layui.popup.failure('请输入备注')
            }

            layer.close(index)
            let loading = layer.load()
            $.ajax({
              url: REMARK_API,
              data: { id: ids, remark: remark },
              dataType: 'json',
              type: 'post',
              success: function (res) {
                layer.close(loading)
                if (res.code) {
                  return layui.popup.failure(res.msg)
                }
                return layui.popup.success('操作成功', refreshTable)
              },
              error: function () {
                layer.close(loading)
                return layui.popup.failure('网络错误')
              },
            })
          })
        }

        // 续费操作
        let __renew_operate__ = function (obj) {
          let data = table.checkStatus(obj.config.id).data
          if (!data || !data.length) return layui.popup.warning('未选中数据')

          let selectTime = null

          const renderPirce = (
            item,
            ops = {
              success: 0,
              error: 0,
            }
          ) => {
            const len = data.length
            const money = parseFloat(item.money)
            const totalMoney = money * len
            // $('#renew-wrapper .tips-left').html(
            //   `已选续费数量<span>${len}</span>条，应付<span>${totalMoney}</span>积分， 成功<span>${ops.success}</span>条，失败<span>${ops.error}</span>条`
            // )
            $('#renew-wrapper .tips-left').html(`已选续费数量<span>${len}</span>条，应付<span>${totalMoney}</span>积分`)
          }

          const renderRenewTable = function () {
            layui.table.render({
              elem: '#renew-table',
              height: 'full',
              data,
              skin: 'line',
              toolbar: false,
              cols: [
                [
                  { field: 'ip', title: 'IP' },
                  { field: 'account', title: '用户名' },
                  { field: 'expire_time', title: '到期时间' },
                  {
                    field: 'status',
                    title: '状态',
                    templet: function (d) {
                      return '未续费'
                      // return d.status == 1 ? '已续费' : '未续费'
                    },
                  },
                ],
              ],
              done: function () {
                // 先解绑之前的事件，防止重复绑定
                $('#confirm-renew').off('click');
                $('#cancel-renew').off('click');

                // 注册确定与取消事件
                $('#confirm-renew').on('click', function () {
                  // NOTE: 确定续费接口
                  layui.layer.load()
                  APILIST.postRenewDuration(
                    {
                      user_id: defaultUserId, // UserId
                      line_id: defaultLineId, // 线路ID
                      duration: selectTime.duration, // duration 时长类型
                      ids: data.map((item) => item.id), // 订单节点ID
                    },
                    function (res) {
                      layui.layer.closeAll('loading')
                      layui.notice.info(res.msg)
                      // TODO: 此处应该由后端返回 (成功&失败数量)
                      renderPirce(selectTime, {
                        success: data.length,
                        error: 0,
                      })
                      setTimeout(() => {
                        layer.closeAll()
                        window.refreshTable()
                      }, 1100)
                    }
                  )
                })

                // cancel window.
                $('#cancel-renew').on('click', function () {
                  layer.closeAll()
                })
              },
            })

            APILIST.getNodeRenewDurationList({
              user_id: defaultUserId, // UserId
              line_id: defaultLineId,
            }, function (list) {
              const thirdData = list[2]

              const getDefault = (item) => {
                if (!item) return ''
                return [`${item.duration}|${item.money}`]
              }

              renderPirce(thirdData)

              selectTime = thirdData

              layui.xmSelect.render({
                el: '#select-time',
                name: 'select-time',
                initValue: getDefault(thirdData),
                filterable: false,
                direction: 'up',
                data: list.map((item) => ({
                  ...item,
                  name: item.name,
                  value: `${item.duration}|${item.money}`,
                })),
                model: { icon: 'hidden', label: { type: 'text' } },
                clickClose: true,
                radio: true,
                on: function (selData) {
                  if (!selData) return
                  const sel = selData.arr[0]
                  renderPirce(sel)
                  selectTime = sel
                },
              })
            })
          }

            layer.open({
                type: 1,
                title: '续费',
                shade: 0.1,
                maxmin: false,
                area: [common.isModile() ? '100%' : '60%', common.isModile() ? '100%' : '95%',],
                content: $('#renew-wrapper'),
                success: function () {
                    renderRenewTable()
                },
            })
        }

        //   过户操作
        let __transfer_ownership__ = function (obj) {
          const data = table.checkStatus(obj.config.id).data
          if (!data || !data.length) return layui.popup.warning('未选中数据')
          const ipIds = data.map((item) => item.id)
          let OtherData = {
            username: '',
          }

          const renderTransferTable = function () {
            layui.table.render({
              elem: '#transfer-os-table',
              // url: APILIST.getInvitationUserListURL,
              url: '',
              method: 'post',
              where: OtherData,
              data: [],
              // 此处需要把要过户的IP列表放到data数据中 方便取用
              parseData: function (res) {
                return {
                  code: res.code, //解析接口状态
                  msg: res.message, //解析提示文本
                  // count: res.total, //解析数据长度
                  data: res.data.map((item) => {
                    // data: [
                    //   {
                    //     account: 'text data.',
                    //   },
                    // ].map((item) => {
                    return {
                      ...item,
                      _ips: ipIds,
                    }
                  }),
                }
              },
              height: 'full',
              skin: 'line',
              toolbar: false,
              cols: [
                [
                  { field: 'account', title: '用户名' },
                  {
                    field: 'status',
                    title: '认证状态',
                    templet: function (d) {
                      return d.status == 1 ? '已认证' : '未认证'
                    },
                  },
                  {
                    title: '操作',
                    toolbar: '#transfer-os-bar',
                    align: 'center',
                    fixed: 'right',
                    width: 120,
                  },
                ],
              ],
              done: function () {
                // 查询接口
                $('#search-users').on('click', function () {
                  const username = $('input.transfer-input').val()
                  table.reload('transfer-os-table', {
                    url: APILIST.getInvitationUserListURL,
                    where: {
                      username,
                      user_id: defaultUserId
                    },
                    // done(){} // 可以清空数据
                  })
                })

                //   cancel window.
                $('#search-users-cancel').on('click', function () {
                  layer.closeAll()
                  $('input.transfer-input').val('')
                })
              },
            })
          }

          layer.open({
            type: 1,
            title: '过户',
            shade: 0.1,
            maxmin: false,
            area: [common.isModile() ? '100%' : '60%', common.isModile() ? '100%' : '95%',],
            content: $('#transfer-ownership-wrapper'),
            success: function () {
              renderTransferTable()
            },
            cancel(index) {
              layer.close(index)
              $('input.transfer-input').val('')
            },
          })
        }

        // NOTE: 过户操作
        table.on('tool(transfer-os-table)', function (obj) {
          if (obj.event === 'transfer-ownership') {
            layer.load()
            APILIST.setTransferUser(
              {
                line_id: defaultLineId,
                to_user_id: obj.data.id,
                ids: obj.data._ips,
                user_id: defaultUserId,
              },
              (res) => {
                layer.closeAll('loading')
                layui.notice.info(res.msg)
                window.refreshTable()
                window.setTimeout(() => {
                  layui.layer.closeAll()
                }, 1000)
              }
            )
          }
        })

        // 平均时间
        let __average_time__ = function (obj) {
          let data = table.checkStatus(obj.config.id).data
          if (!data || !data.length) return layui.popup.warning('未选中数据')
          const maxTime = Math.max(
            ...data.map((item) => new Date(item.expire_time).getTime())
          )

          let expireTime = ''
          let minTime = '-1'
          let currentTime = ''

          if (maxTime) {
            let date = new Date(maxTime)
            expireTime = `${date.getFullYear()}-${
              date.getMonth() + 1
            }-${date.getDate()}`
            // ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}
          }

          // 获取用户信息
          // APILIST.getBaseInfo((user_extend) => {
          //   const formatList = setIndexInfo(user_extend, defaultLineId)
          //   const cur = formatList.find((item) => item.default && item.show)
          //   if (cur) currentTime = cur.type
          //   renderBNTimes(formatList)
          //   // 时长操作逻辑
          // })

          if (!$('.bn-times ul li').length) {
            // bn-times
            APILIST.getAverageTimeList((data) => {
              // console.log('%c ??? >>>', 'background: blue; color: #fff', data)
              // {min: 1, max: 10, amount: '5'}
              const fragments = new DocumentFragment()
              $.each(data, (index, { min, max, amount }) => {
                fragments.append($(`<li>${min}~${max}天:${amount}金币</li>`)[0])
              })

              $('.bn-times ul').append(fragments)
            })
          }

          layui.laydate.render({
            elem: '#expire_time_average_time',
            type: 'date',
            min: expireTime, // 2012-1-1
            // max: '', // max: '2017-12-31'
            done(value, date, endDate) {
              currentTime = value
              // console.log(value) //得到日期生成的值，如：2017-08-18
              // console.log(date) //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
              // console.log(endDate) //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
            },
          })

          // $('.bn-times').on(
          //   'click',
          //   'button:not([data-type="btn"])',
          //   function () {
          //     const $btns = $('.bn-times button:not([data-type="btn"])')
          //     const $btn = $(this)
          //     const primaryStr = 'pear-btn-primary'
          //     const isSel = $btn.hasClass(primaryStr)
          //     let score = $btn.attr('data-score')
          //     let type = $btn.attr('data-type')
          //     currentTime = type
          //     $.each($btns, (index, btn) => $(btn).removeClass(primaryStr))
          //     $btn[isSel ? 'removeClass' : 'addClass'](primaryStr)
          //   }
          // )

          const renderAverageTimeTable = function () {
            layui.table.render({
              elem: '#average-timebox',
              height: 'full',
              data: data,
              skin: 'line',
              toolbar: false,
              cols: [
                [
                  {
                    field: 'region_id',
                    title: '所属节点',
                    templet: function (d) {
                      let field = 'region_id'
                      if (typeof d[field] == 'undefined') return ''
                      let items = []
                      layui.each((d[field] + '').split(','), function (k, v) {
                        items.push(apiResults[field][v] || v)
                      })
                      return util.escape(items.join(','))
                    },
                  },
                  { field: 'ip', title: 'IP' },
                  { field: 'port', title: '端口', width: 100 },
                  { field: 'account', title: '用户名' },
                  { field: 'pass', title: '密码' },
                  { field: 'expire_time', title: '到期时间' },
                  {
                    field: 'status',
                    title: '状态',
                    templet: (d) => (d.status == 1 ? '已平均' : '待平均'),
                  },
                ],
              ],
            })
          }

          layer.open({
            type: 1,
            title: '平均时间',
            shade: 0.1,
            maxmin: false,
            area: [common.isModile() ? '100%' : '60%', common.isModile() ? '100%' : '95%',],
            content: $('#average-time-wrapper'),
            btnAlign: 'c',
            btn: ['确认平均', '取消'],
            yes: function (index, layero) {
              // NOTE: 确认平均
              if (currentTime == '') return layer.msg('请选择平均时间')
              layer.load()
              APILIST.setAverageTime(
                {
                  line_id: defaultLineId,
                  ids: data.map((item) => item.id),
                  date: currentTime,
                  user_id: defaultUserId
                },
                (res) => {
                  layer.close(index)
                  layer.closeAll('loading')
                  layui.notice.info(res.msg)
                  window.refreshTable()
                }
              )
            },
            btn2: function (index, layero) {
              layer.close(index)
            },
            success: function () {
              renderAverageTimeTable()
            },
          })
        }

        // 修改密码
        let __change_password__ = function () {
          let data = table.checkStatus('data-table').data
          if (!data || !data.length) return layui.popup.warning('未选中数据')
          $('#change-password-input').val('')
          let tableInstance = null

          const renderChangePasswordTable = function () {
            tableInstance = layui.table.render({
              elem: '#change-password',
              height: 'full',
              data: data,
              skin: 'line',
              toolbar: false,
              cols: [
                [
                  {
                    field: 'region_id',
                    title: '所属节点',
                    templet: function (d) {
                      let field = 'region_id'
                      if (typeof d[field] == 'undefined') return ''
                      let items = []
                      layui.each((d[field] + '').split(','), function (k, v) {
                        items.push(apiResults[field][v] || v)
                      })
                      return util.escape(items.join(','))
                    },
                  },
                  { field: 'ip', title: 'IP' },
                  { field: 'account', title: '用户名' },
                  { field: 'pass', title: '密码' },
                  {
                    field: 'newpass',
                    title: '新密码',
                    templet: function (d) {
                      return `<input type="text" placeholder="请输入新密码" name="newpass" class="layui-input layui-input-sm" style="height: 100%" />`
                    },
                  },
                  {
                    field: 'status',
                    title: '状态',
                    templet: (d) => (d.status == 1 ? '已修改' : '待修改'),
                  },
                ],
              ],
            })

            //   layui.table.on('edit(test)', function (obj) {
            //     //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            //     console.log(obj.value) //得到修改后的值
            //     console.log(obj.field) //当前编辑的字段名
            //     console.log(obj.data) //所在行的所有相关数据
            //   })
          }

          layer.open({
            type: 1,
            title: '修改密码',
            shade: 0.1,
            maxmin: false,
            area: [common.isModile() ? '100%' : '60%', common.isModile() ? '100%' : '95%',],
            content: $('#change-password-wrapper'),
            btnAlign: 'c',
            btn: ['确认修改', '取消'],
            yes: function (index, layero) {
              // NOTE: 修改密码确认
              const globalPass = $('#change-password-input').val()
              const formData = {
                // type 类型1=批量修改,2=列表修改
                type: globalPass ? 1 : 2,
                password: globalPass,
                data: [],
              }
              const inputs = $('#change-password-wrapper input[name="newpass"]')
              let pass = false
              $.each(data, function (index, item) {
                formData.data.push({
                  id: item.id,
                  password: $(inputs[index]).val(),
                })
              })
              for (let i = 0; i < formData.data.length; i++) {
                const item = formData.data[i]
                if (!item.password) {
                  pass = true
                  break
                }
              }

              // 列表修改时；需要判断是否有密码
              if (formData.type == 2 && pass) {
                layer.msg('密码尚未完善')
                return
              }

              layer.load()
              APILIST.putUserUpdatePwd(
                {
                  user_id: defaultUserId,
                  line_id: defaultLineId,
                  ...formData,
                },
                (res) => {
                  layer.closeAll()
                  layui.notice.info(res.msg)
                  window.refreshTable()
                }
              )
            },
            btn2: function (index, layero) {
              layer.close(index)
            },
            success: function () {
              renderChangePasswordTable()
            },
          })
        }

        // 渲染Dropdown
        // 操作调换IP.
        function renderDropdown(dropdown, data) {
          dropdown.render({
            elem: '#more_change_ip',
            id: 'more_change_ip',
            data: [
              {
                title: '同地区调换',
                id: 1,
              },
              {
                title: '随机地区调换',
                id: 2,
              },
              {
                title: '自选地区调换',
                id: 3,
              },
              {
                title: '游戏调换',
                id: 4,
              },
            ],
            // ready: function (elemPanel, elem) {
            //   console.log(elemPanel) // 得到组件面板的 DOM 对象
            //   console.log(elem) // 得到基础参数 elem 所绑定的元素 DOM 对象
            // },
            click: function (data, othis) {
              // console.log(data) // 得到当前所点击的菜单项对应的数据
              // console.log(othis) // 得到当前所点击的菜单项 DOM 对象
              // console.log(this.elem) //得到当前组件绑定的原始 DOM 对象，批量绑定中常用。
              executeAction(data)
            },
          })
        }

        function executeAction(action) {
          const $ = layui.$
          const { id, title } = action
          const data = layui.table.checkStatus('data-table').data
          if (!data || !data.length) return layui.popup.warning('未选中数据')

          // 多地区不可调换
          var a = data[0]['game_id'],
                  i = !1
          data.forEach(function (e, n) {
            if (e['game_id'] != a && 0 == i)
              return layui.popup.warning('不能同时调换多个项目'), void (i = !0)
          })
          if (i) return

          // 1 数据过期不能选择
          const currentTimeStamp = Date.now()
          const hasExpired = data.some(
                  (item) => new Date(item.expire_time).getTime() < currentTimeStamp
          )

          if (hasExpired) return layui.popup.warning('选择的数据已过期')

          // 游戏调换
          if(id == 4){
            exchangeGame(data);
            return;
          }

          // Reset dialog context.
          $('#change-same-area-wrapper #change-same-area-table').html('')
          $(
                  '#change-same-area-wrapper div[lay-id="change-same-area-table"]'
          ).remove()
          $('#change-same-area-wrapper form .layui-form-item:eq(2)').hide()

          $(
                  'form[lay-filter="change-same-area-form"] > div.layui-form-item:eq(1)'
          ).hide()

          $('div[lay-filter="change-same-area-tab"]')[
                  id === 3 ? 'show' : 'hide'
                  ]()

          const executeSomething = () => {
            switch (id) {
              case 1:
                handleChangeSameArea(data, undefined, {
                  apiResults,
                })
                break
              case 2:
                handleChangeSameArea(data, true, {
                  apiResults,
                })
                break
              case 3:
                handleChangeAreaIP(data)
                break
            }
          }

          if (!window.Accounts) {
            APILIST.getCustomAccountList((data = []) => {
              window.Accounts = data
              executeSomething()
            })
          } else executeSomething()
        }

        // 游戏调换
        let exchangeGame = function(data){
          const ids = data.map((item) => item.id)
          layer.open({
            type: 2,
            title: "游戏调换",
            shade: 0.1,
            maxmin: true,
            area: [common.isModile()?"100%":"60%", common.isModile()?"100%":"95%"],
            content: ORDERDETAIL_GAME_URL + "?" + 'line_id=' +defaultLineId+ '&ids=' +ids+'&user_id=' +defaultUserId,
            skin: ''
          });
        }

        // 自动续费开启/关闭
        let renewAutoOpen = function (obj, status) {
          let checkIds = common.checkField(obj, PRIMARY_KEY)
          if (checkIds === '') {
            layui.popup.warning('未选中数据')
            return false
          }
          doRenewAutoOpen(checkIds.split(','), status)
        }

        // 执行自动续费开启/关闭
        let doRenewAutoOpen = function (ids, status) {
          let title = ''
          let content = ''
          if (status == 1) {
            title = '开启自动续费'
            content =
                    '<div id="" class=""><strong><font color="red">确定要开启自动续费？<br/>' +
                    configText +
                    '</font></strong></div>'
          } else {
            title = '关闭自动续费'
            content =
                    '<div id="" class=""><strong><font color="red">确定要关闭自动续费？</font></strong></div>'
          }

          layer.open({
            // type: 1,
            title: title,
            shade: 0.1,
            maxmin: true,
            content: content,
            skin: '',
            btn: ['确定', '取消'],
            yes: function (index, layero) {
              $.ajax({
                url: RENEW_AUTO_OPEN_API,
                data: { ids: ids, status: status,user_id:defaultUserId},
                dataType: 'json',
                type: 'post',
                success: function (res) {
                  layer.close(index)
                  if (res.code) {
                    return layui.popup.failure(res.msg)
                  }
                  return layui.popup.success(res.msg, refreshTable)
                },
                error: function () {
                  layer.close(index)
                  return layui.popup.failure('网络错误')
                },
              })
            },
            btn2: function (index, layero) {
              layer.close(index)
            },
          })
        }

        // 解绑
        let bind = function (obj) {
          let checkIds = common.checkField(obj, PRIMARY_KEY)
          if (checkIds === '') {
            layui.popup.warning('未选中数据')
            return false
          }
          doBind(checkIds.split(','))
        }

        // 执行解绑
        let doBind = function (ids) {
          layer.confirm('确定解绑?', {icon: 3, title: '解绑',}, function (index) {
                    layer.close(index)
                    let loading = layer.load()
                    $.ajax({
                      url: BIND_API,
                      data: {ids:ids,user_id:defaultUserId},
                      dataType: 'json',
                      type: 'post',
                      success: function (res) {
                        layer.close(loading)
                        if (res.code) {
                          return layui.popup.failure(res.msg)
                        }
                        layui.notice.info(res.msg)
                        window.refreshTable()
                        return true;
                      },
                      error: function () {
                        layer.close(loading)
                        return layui.popup.failure('网络错误')
                      },
                    })
                  }
          )
        }

        /*-------按钮操作 end----------*/


        if(defaultUserId > 0){
          // 渲染选项卡
          let lineSelectData = <?=$line_list?>;
          layui.use(["jquery", "popup"], function() {
            let html = '';
            $.each(lineSelectData,function(index,value){
              if(value.id == defaultLineId){
                html += "<li class='layui-this' lay-submit lay-filter='table-type' data-type='"+value.id+"'>" + value.name + "</li>";
              } else{
                html += "<li lay-submit lay-filter='table-type' data-type='"+value.id+"'>" + value.name + "</li>";
              }
            })
            $("#typeData").html(html);
            $('#line_id').val(defaultLineId);
          });

          // 选项卡点击事件
          form.on("submit(table-type)", function(data) {
            let type = $(this).data('type');
            $('#line_id').val(type);
            defaultLineId = type // NOTE: 选项卡更换分区时 切换默认的展示分区、用于其他接口使用
            data.field.line_id = type;
            data.field.field = PRIMARY_KEY;
            data.field.order = 'desc';
            console.log(data,'table-type');
            table.reload("data-table", {
              page: {
                curr: 1
              },
              where: data.field
            })
            return false;
          });
        }
      })
    </script>
  </body>
</html>
